﻿using MediumApi.Db;
using MediumApi.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.VisualBasic;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MediumApi.Tools
{
    public class Tools
    {
        public static async Task<bool> AddFlieAsync(IFormFile formFile, string Id, int num, int type)
        {
            if (type == 1)
            {
                int index = formFile.FileName.ToLower().IndexOf(".png");
                string fileName = string.Empty;
                if (index != -1)
                {
                    fileName = Id + num + formFile.FileName.Substring(index);
                }
                else if (index == -1)
                {
                    index = formFile.FileName.ToLower().IndexOf(".jpg");
                    //错误删除图片
                    if (index == -1)
                    {
                        string searchPattern = Id; // 你希望在文件名中包含的字符串

                        // 获取所有文件的路径
                        string[] filePaths = Directory.GetFiles($"{AppSettingHelper.GetConfig("Path")["PicturePath"]}");

                        // 使用LINQ查询包含特定字符串的文件
                        var matchingFiles = filePaths.Where(path => Path.GetFileName(path).Contains(searchPattern, StringComparison.OrdinalIgnoreCase));
                        foreach (var filePath in matchingFiles)
                        {
                            if (System.IO.File.Exists(filePath)) // 确保是文件
                            {
                                System.IO.File.Delete(filePath); // 删除文件
                            }
                        }

                        return false;
                    }
                    fileName = Id + num + formFile.FileName.Substring(index);
                }
                using (var stream = System.IO.File.Create($"{AppSettingHelper.GetConfig("Path")["PicturePath"]}" + fileName))
                {
                    await formFile.CopyToAsync(stream);

                }
                return true;
            }
            else if (type == 2)
            {
                int index = formFile.FileName.ToLower().IndexOf(".mp4");
                string fileName = string.Empty;
                if (index != -1)
                {
                    fileName = Id + formFile.FileName.Substring(index);
                    using (var stream = System.IO.File.Create($"{AppSettingHelper.GetConfig("Path")["VideoPath"]}" + fileName))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
                else
                {
                    return false;
                }
                return true;
            }
            return false;
        }

        public static string GenerateTimestampRandomCode()
        {
            long timestamp = DateTime.Now.Ticks;
            Random random = new Random((int)timestamp);

            // 组合时间戳和随机数生成6位数
            int code = random.Next(100000, 1000000);

            return code.ToString();
        }
        public static bool CallInterface(string Url, string jsonParas, string model)
        {
            string strURL =  Url;
            try
            {

                //创建一个HTTP请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式
                request.Method = model;
                request.Timeout = 20000;
                //request.Connection["token"]=
                //内容类型
                request.UserAgent = "BegreenRuntime/1.0";
                request.ContentType = "application/json";

                if (model == "POST" && !string.IsNullOrEmpty(jsonParas))
                {
                    //设置参数，并进行URL编码
                    string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);

                    byte[] payload;
                    //将Json字符串转化为字节
                    payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                    //设置请求的ContentLength
                    request.ContentLength = payload.Length;
                    //发送请求，获得请求流
                    Stream writer;
                    try
                    {
                        writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message + "2");
                    }

                    //将请求参数写入流
                    writer.Write(payload, 0, payload.Length);
                    writer.Close();//关闭请求流
                }
                HttpWebResponse response;
                try
                {

                    //获得响应流
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    throw new Exception(ex.Message + "3");
                    //response = ex.Response as HttpWebResponse;

                }

                Stream s = response.GetResponseStream();
                StreamReader sRead = new StreamReader(s);
                string postContent = sRead.ReadToEnd();
                sRead.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public static string Sha256(string data) 
        {
            // 密钥，实际应用中应该以安全的方式生成和存储密钥
            string key = "}xj5<344Zg68"; // 注意：密钥长度至少为16字节，最好是32字节

            // 将密钥和数据进行加密（实际上是生成签名）
            byte[] keyBytes = Encoding.UTF8.GetBytes(key);
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            byte[] hash;

            using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
            {
                hash = hmac.ComputeHash(dataBytes);
            }

            // 将生成的哈希值转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hash)
            {
                sb.AppendFormat("{0:x2}", b);
            }
            return sb.ToString();
        }
    }
}
